<template>
  <basic-container>
    <el-form ref="form" searchform :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
      <el-row>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">租户:</div>
          <el-select v-model="form.tenantId" clearable filterable placeholder="请选择租户" size="mini" style="width: 60%"
                     @change="searchForm">
            <el-option
              v-for="item in tenantList"
              :key="item.tenantId"
              :label="item.tenantName"
              :value="item.tenantId">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">订单名称:</div>
          <el-select v-model="form.offerIdList" clearable multiple filterable placeholder="请选择订单名称" size="mini" style="width: 60%"
                     @change="()=>{rebuildPlatformIdList();searchForm();}">
            <el-option
              v-for="item in tenant.offerList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">账户ID:</div>
          <el-select v-model="form.platformIdList" clearable multiple filterable placeholder="请选择账户ID" size="mini" style="width: 60%"
                     @change="searchForm">
            <el-option
              v-for="item in tenant.platformIdList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">广告媒体:</div>
          <el-select v-model="form.platformList" clearable multiple placeholder="广告媒体" size="mini" style="width: 60%"
                     @change="searchForm">
            <el-option
              v-for="item in platformList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="4" style="min-width: 160px;display:flex;justify-content:flex-end">
          <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
            <el-button :class="upIcon" class="search-circle" @click="unfoldIcon" style="margin-right: 10px"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="清空" placement="top">
            <el-button :class="emptyIcon" class="search-circle" @click="emptyForm"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="搜索" placement="top">
            <el-button type="primary" icon="el-icon-search" size="small" @click="searchForm" style="margin-right: 0">搜索</el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row v-show="searchConceal">
        <el-col span="10" style="min-width:150px">
          <div class="text" style="width: 15%;">更新日期:</div>
          <el-date-picker
            style="width: 60%;"
            v-model="form.updateDate"
            size="mini"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="searchForm">
          </el-date-picker>
        </el-col>
        <el-col span="10" style="min-width:150px">
          <div class="text" style="width: 15%;">报告日期:</div>
          <el-date-picker
            style="width: 60%;"
            v-model="form.reportDate"
            size="mini"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="searchForm">
          </el-date-picker>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">状态:</div>
          <el-select v-model="form.statusList" clearable multiple placeholder="请选择状态" size="mini" style="width: 60%"
                     @change="searchForm">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">异常原因:</div>
          <el-select v-model="form.exceptionCodesList" clearable multiple placeholder="请选择异常原因" size="mini" style="width: 60%"
                     @change="searchForm">
            <el-option
              v-for="item in exceptionCodesList"
              :key="item.code"
              :label="item.code + '-' + item.description"
              :value="item.code">
            </el-option>
          </el-select>
        </el-col>
      </el-row >
    </el-form>

    <avue-crud
      :table-loading="loading"
      :data="data"
      :option="option"
      :page.sync="page"
      ref="crud"
      :cell-class-name="getCellClassName"
      @on-load="onLoad"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template slot-scope="scope" slot="exceptionCodes">
        <el-tooltip effect="dark" v-if="scope.row.exceptionCodes != '' && scope.row.exceptionCodes != null" :content="getExceptionCodeDescription(scope.row.exceptionCodes)" placement="top-end">
          <div style="border-bottom: 1px solid blue;color: red;cursor: pointer;text-align:center;">
            {{scope.row.exceptionCodes}}
          </div>
        </el-tooltip>
      </template>
      <template slot="Costrate" slot-scope="scope" >
        <el-tag>{{(1-scope.row.cost/scope.row.importCost)*100}}%</el-tag>
      </template>
      <template slot="menuLeft" slot-scope="{size}">
        <el-button  type="primary" size="small" :disabled="!(questionArchiveIds.length > 0)" @click="questionArchive">问题归档</el-button>
        <el-button  type="primary" size="small" :disabled="!(form.tenantId != null && form.tenantId != '' && selectionList != null && selectionList.length > 0)" @click="manualPulling">手动拉取</el-button>
        <el-button  type="primary" size="small" :disabled="!(form.tenantId != null && form.tenantId != '')">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="/api/beetles-offer/beetlesaccountexception/importExecl"
            :show-file-list="false"
            :headers="importExcel.headers"
            accept=".xlsx,.xls"
            :on-success="handleSuccess"
            :data="{tenantId: form.tenantId}"
          >
            导入文件
          </el-upload>
        </el-button>

        <el-button  type="primary" size="small" @click="refreshChange" >刷新校验结果</el-button>
        <el-button  type="primary" size="small" @click="downloadExcel" >下载导入模板</el-button>
      </template>

    </avue-crud>
    <div id="downloadExcel"></div>
  </basic-container>
</template>
<script>

  import {getList,getTenantParamsList,questionArchive,manualPulling} from "@/api/verification/AccountexpenseVerification";
  import {getExceptionCodeList} from "@/api/verification/beetlesaccountexception";
  import {getActiveTenantList} from "@/api/system/tenant";
  import {refineObject, findObject, findByProp, generateTable, exportExcel} from "@/util/util";
  import {getSysDictList} from '@/api/system/dict'
  import Moment from 'moment';
  import website from "@/config/website";
  import {getToken} from "@/util/auth";

export default {
  name: "AccountexpenseVerification",
  data() {
    let start = Moment(new Date()).subtract(14, "days").toDate();
    let end = Moment(new Date()).subtract(1, "days").toDate();
    return{
      option: {
        addBtn: false,
        menu: false,
        index: true,
        selection: true,
        align:'center',
        menuAlign:'center',
        excelBtn: true,
        excelBtnText:"导出数据",
        column:[
          {
            label:'报告时间',
            prop:'reportDate',
            width: 150,
            fixed: true,
          },
          {
            label:'账户ID',
            prop:'accountId',
            fixed: true,
          },
          {
            label:'账户名称',
            prop:'accountName',
          },
          {
            label:'订单ID',
            prop:'offerId'
          },
          {
            label:'订单名称',
            prop:'offerName',
          },
          {
            label:'广告媒体',
            prop:'platform',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label:'花费',
            prop:'cost'
          },
          {
            label:'账户货币',
            prop:'currency'
          },
          {
            label:'花费(USD)',
            prop:'costUsd'
          },
          {
            label:'导入花费',
            prop:'importCost'
          },
          {
            label:'花费差异率',
            prop:'costDiffRate'
          },
          {
            label:'账户时区',
            prop:'timezone'
          },
          {
            label:'拉取耗时(s)',
            prop:'timeSpent'
          },
          {
            label:'状态',
            prop:'status',
            type: "select",
            dicData:  [
              {label: '异常',       value: 0},
              {label: '正常',       value: 1},
              {label: '归档',       value: 2},
            ],
          },
          {
            label:'异常原因',
            prop:'exceptionCodes',
          },
          {
            label:'首次拉取时间',
            prop:'createTime'
          },
          {
            label:'更新时间',
            prop:'updateTime'
          },
        ]
      },
      data: [],
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pageSizes: [10,15,20,30,40,50,100],
      },
      selectionList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '过去三十天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "months").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去十四天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(14, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去七天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(7, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '昨天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, start]);
          }
        },{
          text: '今天',
          onClick(picker) {
            let start = new Date();
            picker.$emit('pick', [start, start]);
          }
        }]
      },
      query: {},
      form: {
        tenantId: '',
        offerIdList: [],
        platformIdList: [],
        platformList: [],
        updateDate: [start,end],
        reportDate: [start,end],
        exceptionCodesList: [],
        statusList: [0],
      },
      rules: {
        tenantId: [{required: true, message: '请选择租户',trigger: 'change'}]
      },
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,

      exceptionCodesList: [],
      tenantList: [],
      tenant: {
        offerList: [],
        platformIdList: [],
        offerAccountIdList: [],
      },
      statusList: [
        {label: '异常',       value: 0},
        {label: '正常',       value: 1},
        {label: '归档',       value: 2},
      ],

      importExcel: {
        headers: {}
      },
    }
  },
  watch: {
    'form.tenantId': {
      deep: true,
      handler(val,old) {
        if (val === old) {
          return
        }
        this.form.platformIdList = [];
        this.form.offerList = [];

        this.tenant.offerAccountIdList = [];
        this.tenant.offerList = [];
        this.tenant.platformIdList = [];
        this.selectionClear();
        if(val != null && val != '') {
          this.loadTenantParams(val);
        }
      }
    },
  },
  computed: {
    questionArchiveIds() {
      let ids = [];
      if(this.selectionList != null && this.selectionList.length > 0) {
        this.selectionList.forEach((row)=>{
          if(row.status != 2) {
            ids.push(row.id);
          }
        })
      }
      return ids;
    },
  },
  created() {
    this.form.tenantId=this.$route.params.tenantId;
    getActiveTenantList().then((res)=>{
      this.tenantList=res.data.data;
    });
    getExceptionCodeList().then((res)=>{
      this.exceptionCodesList=res.data;
    });
    getSysDictList("platforms").then((map)=>{
      this.platformList = map['platforms'];
    });
    if(this.form.tenantId != null && this.form.tenantId != '') {
      this.searchForm();
    }

    this.importExcel.headers[website.tokenHeader] = getToken();
  },
  methods:{
    unfoldIcon(){
      if (this.upIcon === 'el-icon-arrow-down'){
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      }else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    loadTenantParams(tenantId) {
      getTenantParamsList(tenantId).then(res=>{
        if(res.data.success) {
          this.tenant.offerAccountIdList = res.data.data.offerAccountIdList;
          let offerIdList = [];
          let offerList = [];
          this.tenant.offerAccountIdList.forEach((ele)=>{
            if(!offerIdList.includes(ele['offer_id'])) {
              offerIdList.push(ele['offer_id']);
              offerList.push({id: ele['offer_id'], name: ele['offer_name']});
            }
          });
          this.tenant.offerList = offerList;
          this.rebuildPlatformIdList();
        }
      });
    },
    rebuildPlatformIdList() {
      let platformIdList = [];
      this.tenant.offerAccountIdList.forEach((ele)=>{
        if(!platformIdList.includes(ele['account_id'])) {
          if(this.form.offerIdList == null || this.form.offerIdList.length == 0) {
            platformIdList.push(ele['account_id']);
          } else {
            if(this.form.offerIdList.includes(ele['offer_id'])) {
              platformIdList.push(ele['account_id']);
            }
          }
        }
      });
      this.tenant.platformIdList = platformIdList;
      let formPlatformIdList = [];
      this.form.platformIdList.forEach(platformId=>{
        if(platformIdList.includes(platformId)) {
          formPlatformIdList.push(platformId);
        }
      });
      if(formPlatformIdList.length != this.form.platformIdList.length) {
        this.form.platformIdList = formPlatformIdList;
      }
    },
    getExceptionCodeDescription(codes) {
      if(codes == '') {
        return '';
      } else {
        let codeList = codes.split(',');
        let descriptionList = [];
        codeList.forEach((code)=>{
          descriptionList.push(findByProp(this.exceptionCodesList,code,'code','description'));
        });
        return descriptionList.join(',')
      }
    },
    downloadExcel() {
      let tableData = {
        title: null,
        headers: [],
        rowList: [],
        bottom: [],
      };
      tableData.headers.push({data: 'reportDate', style: 'text-align: right;'});
      tableData.headers.push({data: 'accountId', style: 'text-align: right;'});
      tableData.headers.push({data: 'cost', style: 'text-align: right;'});
      tableData.headers.push({data: 'createTime', style: 'text-align: right;'});

      let row = [];
      row.push({data: 'YYYY-MM-DD', style: 'text-align: right;'});
      row.push({data: 'xxx-xxx-xxxxD', style: 'text-align: right;'});
      row.push({data: '123.45', style: 'text-align: right;'});
      row.push({data: 'YYYY-MM-DD hh:mm:ss', style: 'text-align: right;'});

      tableData.rowList.push(row);
      exportExcel('downloadExcel',tableData.title,tableData.headers,tableData.rowList,tableData.bottom,'账户花费校验模板.xls');
    },
    handleSuccess(val){
      if(val==true){
        this.$message({
          message: '导入成功',
          type: 'success'
        });
        this.refreshChange();
      }else{
        this.$message({
          message: '导入失败',
          type: 'success'
        })
      }
    },
    manualPulling(cmd){
      if(cmd != 'exec') {
        let sortDataList = [];
        this.selectionList.forEach((row)=>{
          let sortData = findObject(sortDataList,row.platform,'platform');
          if(sortData == null) {
            sortData = {
              platform: row.platform,
              list: [],
            };
            sortData.list.push(row);
            sortDataList.push(sortData);
          } else {
            sortData.list.push(row);
          }
        });
        let htmlMsg = [];
        sortDataList.forEach((sortData)=>{
          if(htmlMsg.length > 0) {
            htmlMsg.push('<div><br></div>');
          }
          htmlMsg.push('<div>媒体：' + sortData.platform + '</div>');
          sortData.list.forEach(row=>{
            htmlMsg.push('<div>账户ID：' + row.accountId + '； 数据时间：' + row.reportDate + '</div>');
          });
        });

        this.$confirm(htmlMsg.join(''), '提示', {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.manualPulling('exec');
        }).catch(()=>{
        }).finally(() => {
        });
        return;
      }

      let beetlesAccountExceptionList = [];
      this.selectionList.forEach((row)=>{
        beetlesAccountExceptionList.push({
          id: row.id,
          accountId: row.accountId,
          platform: row.platform,
          reportDate: row.reportDate
        });
      });
      this.loading = true;
      manualPulling(this.form.tenantId, beetlesAccountExceptionList).then((res)=>{
        if(res.data.success){
          this.$message({
            message: '手动抓取成功',
            type: 'success'
          });
          this.refreshChange();
        }else{
          this.$message({
            message: '手动抓取失败',
            type: 'warning'
          })
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    questionArchive(){
      let ids = this.questionArchiveIds;
      if(ids.length == 0) {
        return;
      }
      this.loading = true;
      questionArchive({tenantId: this.form.tenantId, ids: ids.join(',')}).then((res)=>{
        if(res.data.success == true){
          this.$message({
            message: '归档成功',
            type: 'success'
          });
          this.refreshChange();
        }else{
          this.$message({
            message: '归档失败',
            type: 'warning'
          })
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    searchForm(){
      if(this.form.tenantId == null || this.form.tenantId == '') {
        this.$message.warning('请选择租户');
        return;
      }
      this.query = {
        tenantId: this.form.tenantId,
        offerIdList: this.form.offerIdList.join(","),
        platformIdList: this.form.platformIdList.join(","),
        platformList: this.form.platformList.join(","),
        exceptionCodesList: this.form.exceptionCodesList.join(','),
        statusList: this.form.statusList.join(','),
      };
      if(this.form.updateDate == null || this.form.updateDate.length == 0) {
        this.query.updateTimeList = '';
      } else {
        this.query.updateTimeList = Moment(this.form.updateDate[0]).format('YYYY-MM-DD') + ',' + Moment(this.form.updateDate[1]).format('YYYY-MM-DD')
      }
      if(this.form.reportDate == null || this.form.reportDate.length == 0) {
        this.query.reportDateList = '';
      } else {
        this.query.reportDateList = Moment(this.form.reportDate[0]).format('YYYY-MM-DD') + ',' + Moment(this.form.reportDate[1]).format('YYYY-MM-DD')
      }
      this.page.currentPage = 1;
      this.onLoad(this.page)
    },
    //清空按钮函数
    emptyForm(){
      Object.assign(this.form, {
        offerIdList: [],
        platformIdList: [],
        platformList: [],
        updateDate: null,
        reportDate: null,
        exceptionCodesList: [],
        statusList: [0],
      });
      this.searchForm();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
      this.selectionClear();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      this.selectionClear();
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
      this.selectionClear();
    },
    onLoad(page) {
      if(this.form.tenantId == null || this.form.tenantId == '') {
        return;
      }

      this.loading = true;
      getList(page.currentPage,page.pageSize, this.query).then((res)=>{
        const data = res.data.data;
        this.page.total = data.total;
        this.data = refineObject(data.records,[{from: '-1', to: ''}]);
      }).finally(()=>{
        this.loading = false;
      })
    },
    getCellClassName(scope) {
      if(scope.column.property == 'reportDate' || scope.column.property == 'accountId') {
        return 'fixedText';
      }
      return '';
    },
  },
}
</script>

<style scoped>
  .text{
    width: 45px;
    height:30px;
    float: left;
    font-size: 13px;
    margin-top: 3px;
    color: #72767b
  }


  /deep/[searchform].el-form .el-form-item__error {
    top: -20px;
    left: 45px;
  }
  .search-circle{
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    width: 30px;
    height: 30px;
    padding: 0;
    margin-right: 0;
  }
  /deep/.fixedText {
    background: #e6e6e6;
  }
</style>
